<template>
  <div class="images-page">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>图片管理</span>
          <el-button type="primary" @click="showAddDialog">添加图片</el-button>
        </div>
      </template>

      <!-- 搜索筛选 -->
      <div class="filter-bar">
        <el-input
          v-model="filters.keyword"
          placeholder="搜索标题"
          style="width: 200px"
          clearable
          @keyup.enter="loadImages"
        />
        <el-select
          v-model="filters.categoryId"
          placeholder="选择分类"
          clearable
          style="width: 150px"
        >
          <el-option
            v-for="cat in categories"
            :key="cat.id"
            :label="cat.name"
            :value="cat.id"
          />
        </el-select>
        <el-select
          v-model="filters.status"
          placeholder="状态"
          clearable
          style="width: 120px"
        >
          <el-option label="上架" :value="1" />
          <el-option label="下架" :value="0" />
        </el-select>
        <el-button type="primary" @click="loadImages">搜索</el-button>
        <el-button @click="resetFilters">重置</el-button>
      </div>

      <!-- 批量操作 -->
      <div class="batch-actions" v-if="selectedIds.length > 0">
        <span>已选择 {{ selectedIds.length }} 项</span>
        <el-button @click="batchStatus(1)">批量上架</el-button>
        <el-button @click="batchStatus(0)">批量下架</el-button>
        <el-button type="danger" @click="batchDelete">批量删除</el-button>
      </div>

      <!-- 表格 -->
      <el-table
        :data="images"
        v-loading="loading"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column label="缩略图" width="100">
          <template #default="{ row }">
            <el-image
              :src="row.thumbnail || row.url"
              style="width: 60px; height: 60px"
              fit="cover"
              :preview-src-list="[row.url]"
              preview-teleported
            />
          </template>
        </el-table-column>
        <el-table-column prop="title" label="标题" min-width="150" />
        <el-table-column label="分类" width="100">
          <template #default="{ row }">
            {{ row.category?.name || "-" }}
          </template>
        </el-table-column>
        <el-table-column label="尺寸" width="120">
          <template #default="{ row }">
            {{ row.width && row.height ? `${row.width}×${row.height}` : "-" }}
          </template>
        </el-table-column>
        <el-table-column prop="views" label="浏览" width="80" />
        <el-table-column prop="likes" label="点赞" width="80" />
        <el-table-column label="状态" width="80">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'info'">
              {{ row.status === 1 ? "上架" : "下架" }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="showEditDialog(row)"
              >编辑</el-button
            >
            <el-button
              size="small"
              :type="row.status === 1 ? 'warning' : 'success'"
              @click="toggleStatus(row)"
            >
              {{ row.status === 1 ? "下架" : "上架" }}
            </el-button>
            <el-button size="small" type="danger" @click="handleDelete(row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.pageSize"
          :total="pagination.total"
          :page-sizes="[20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="loadImages"
          @current-change="loadImages"
        />
      </div>
    </el-card>

    <!-- 添加/编辑对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="600px">
      <el-form :model="form" label-width="100px">
        <el-form-item label="标题" required>
          <el-input v-model="form.title" />
        </el-form-item>
        <el-form-item label="图片地址" required>
          <el-input v-model="form.url" />
        </el-form-item>
        <el-form-item label="缩略图地址">
          <el-input v-model="form.thumbnail" />
        </el-form-item>
        <el-form-item label="分类" required>
          <el-select v-model="form.categoryId" style="width: 100%">
            <el-option
              v-for="cat in categories"
              :key="cat.id"
              :label="cat.name"
              :value="cat.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="宽度">
          <el-input-number v-model="form.width" :min="0" />
        </el-form-item>
        <el-form-item label="高度">
          <el-input-number v-model="form.height" :min="0" />
        </el-form-item>
        <el-form-item label="文件大小(字节)">
          <el-input-number v-model="form.size" :min="0" />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import axios from "@/utils/request";

const loading = ref(false);
const images = ref([]);
const categories = ref([]);
const selectedIds = ref([]);
const dialogVisible = ref(false);
const isEdit = ref(false);
const currentId = ref(null);

const filters = reactive({
  keyword: "",
  categoryId: null,
  status: null,
});

const pagination = reactive({
  page: 1,
  pageSize: 20,
  total: 0,
});

const form = reactive({
  title: "",
  url: "",
  thumbnail: "",
  categoryId: null,
  width: null,
  height: null,
  size: null,
});

const dialogTitle = computed(() => (isEdit.value ? "编辑图片" : "添加图片"));

onMounted(() => {
  loadCategories();
  loadImages();
});

async function loadCategories() {
  try {
    const res = await axios.get("/categories", { params: { pageSize: 1000 } });
    categories.value = res.list || [];
  } catch (error) {
    ElMessage.error("加载分类失败");
  }
}

async function loadImages() {
  loading.value = true;
  try {
    const params = {
      page: pagination.page,
      pageSize: pagination.pageSize,
      ...filters,
    };
    const res = await axios.get("/images", { params });
    images.value = res.list || [];
    pagination.total = res.total || 0;
  } catch (error) {
    ElMessage.error("加载图片失败");
  } finally {
    loading.value = false;
  }
}

function resetFilters() {
  filters.keyword = "";
  filters.categoryId = null;
  filters.status = null;
  pagination.page = 1;
  loadImages();
}

function showAddDialog() {
  isEdit.value = false;
  currentId.value = null;
  Object.assign(form, {
    title: "",
    url: "",
    thumbnail: "",
    categoryId: null,
    width: null,
    height: null,
    size: null,
  });
  dialogVisible.value = true;
}

function showEditDialog(row) {
  isEdit.value = true;
  currentId.value = row.id;
  Object.assign(form, {
    title: row.title,
    url: row.url,
    thumbnail: row.thumbnail || "",
    categoryId: row.categoryId,
    width: row.width,
    height: row.height,
    size: row.size,
  });
  dialogVisible.value = true;
}

async function handleSubmit() {
  if (!form.title || !form.url || !form.categoryId) {
    ElMessage.warning("请填写必填项");
    return;
  }

  try {
    if (isEdit.value) {
      await axios.put(`/images/${currentId.value}`, form);
      ElMessage.success("更新成功");
    } else {
      await axios.post("/images", form);
      ElMessage.success("添加成功");
    }
    dialogVisible.value = false;
    loadImages();
  } catch (error) {
    ElMessage.error(error.message || "操作失败");
  }
}

async function toggleStatus(row) {
  try {
    await axios.put(`/images/${row.id}/status`, {
      status: row.status === 1 ? 0 : 1,
    });
    ElMessage.success("操作成功");
    loadImages();
  } catch (error) {
    ElMessage.error("操作失败");
  }
}

async function handleDelete(row) {
  try {
    await ElMessageBox.confirm("确定要删除这张图片吗？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });
    await axios.delete(`/images/${row.id}`);
    ElMessage.success("删除成功");
    loadImages();
  } catch (error) {
    if (error !== "cancel") {
      ElMessage.error("删除失败");
    }
  }
}

function handleSelectionChange(selection) {
  selectedIds.value = selection.map((item) => item.id);
}

async function batchStatus(status) {
  if (selectedIds.value.length === 0) return;

  try {
    await axios.post("/images/batch-status", {
      ids: selectedIds.value,
      status,
    });
    ElMessage.success("操作成功");
    selectedIds.value = [];
    loadImages();
  } catch (error) {
    ElMessage.error("操作失败");
  }
}

async function batchDelete() {
  if (selectedIds.value.length === 0) return;

  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedIds.value.length} 张图片吗？`,
      "提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }
    );

    for (const id of selectedIds.value) {
      await axios.delete(`/images/${id}`);
    }

    ElMessage.success("删除成功");
    selectedIds.value = [];
    loadImages();
  } catch (error) {
    if (error !== "cancel") {
      ElMessage.error("删除失败");
    }
  }
}
</script>

<style scoped>
.images-page {
  height: 100%;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.filter-bar {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
}

.batch-actions {
  margin-bottom: 15px;
  padding: 10px;
  background-color: #f0f9ff;
  border-radius: 4px;
  display: flex;
  align-items: center;
  gap: 10px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>
